package com.yx.pc.api.controller;

import com.yx.common.annotation.Log;
import com.yx.common.utils.PageUtils;
import com.yx.common.utils.Query;
import com.yx.common.utils.R;
import com.yx.modules.api.annotation.LoginUser;
import com.yx.modules.api.entity.TbUser;
import com.yx.pc.api.service.*;
import com.yx.system.dao.TdOnlinePayLogMapper;
import com.yx.system.entity.*;
import com.yx.utils.OrderUtil;
import com.yx.utils.PayStatus;
import com.yx.utils.PayType;
import com.yx.utils.UUIDUtil;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 订单控制器
 */
@RestController
@RequestMapping("/pc/api/order")
public class PcTdOrderController {

    @Autowired
    private PcTdOrderService tdOrderService;

    @Autowired
    private PcTdSectionService tdSectionService;

    @Autowired
    private PcTdBookService tdBookService;

    @Autowired
    private TdOnlinePayLogMapper tdOnlinePayLogMapper;
    @Autowired
    private PcTdWalletPayLogService tdWalletPayLogService;
    @Autowired
    private PcTbUserService tbUserService;

    /**
     * 按ID查询订单
     *
     * @return
     */
    @Log
    @PostMapping("findByUid")
    public R findByUId(int id) {
        return R.ok().put("user", tdOrderService.selectByPrimaryKey(id));
    }

    /**
     * 新增或修改
     *
     * @return
     */
    @Log
    @PostMapping("saveOrUpdate")
    public R saveOrUpdate(TdOrder tdOrder) {
        if (tdOrder.getId() == 0 || tdOrder.getId() == null) {
            tdOrderService.insert(tdOrder);
        } else {
            tdOrderService.updateByPrimaryKey(tdOrder);
        }
        return R.ok();
    }

    /**
     * 删除 (软删除)
     *
     * @return
     */
    @Log
    @PostMapping("delete")
    public R delete(int id) {
        tdOrderService.deleteByPrimaryKey(id);
        return R.ok();
    }

    /**
     * 创建订单并且购买
     *
     * @param tbUser
     * @param sectionid 章节ID
     * @return
     */
    @PostMapping("orderCreate")
    public R orderCreate(@LoginUser TbUser tbUser, String sectionid) {
        JSONArray ja = JSONArray.fromObject(sectionid);
        int totalMoney = 0;
        for (int i = 0; i < ja.size(); i++) {
            TdSection tdSection = tdSectionService.selectByPrimaryKey(Integer.parseInt(ja.get(i).toString()));
            Map<String, Object> map = new HashMap<>();
            map.put("orderStatus", PayStatus.success.getName());
            map.put("uuid", tbUser.getUuid());
            map.put("sectionid", tdSection.getId());
            List<TdOrder> tdOrderList = tdOrderService.queryList(map);
            if (tdOrderList.size() > 0) {
                ja.remove(ja.get(i));
                continue;
            }
            totalMoney += tdSection.getTotalfee();
        }
        if (tbUser.getBalance() < totalMoney) {
            return R.error("用户余额不足！").put("price",(totalMoney-tbUser.getBalance()));
        }
        for (int i = 0; i < ja.size(); i++) {
            TdSection tdSection = tdSectionService.selectByPrimaryKey(Integer.parseInt(ja.get(i).toString()));
            TdBook tdBook = tdBookService.selectByPrimaryKey(tdSection.getBookid());
            TdOrder order = new TdOrder();
            order.setUuid(tbUser.getUuid());
            //为订单赋值
            order.setBillno(OrderUtil.getOrderNo2());
            if (tdBook == null) {
                return R.error("未查询到书籍信息!");
            }
            order.setBookid(tdBook.getId());
            order.setCreatedate(new Date());
            order.setTotalfee(tdSection.getTotalfee());
            order.setUsername(tbUser.getUsername());
            order.setUserphone(tbUser.getMobile());
            order.setSectionid(tdSection.getId());
            order.setOrderstatus(PayStatus.success.getName());
            order.setIspay(true);
            order.setPaytype("out");
            order.setCreateuser(tbUser.getUsername());
            tdOrderService.insert(order);
            //存入支付数据
            TdOnlinePayLog opl = new TdOnlinePayLog();
            opl.setCreatedate(new Date());
            opl.setBillno(order.getBillno());
            opl.setCreateuser(tbUser.getUsername());
            opl.setUuid(UUIDUtil.getUUID());
            opl.setUserid(tbUser.getUserId() + "");
            opl.setPaytype(order.getPaytype());
            opl.setTitle(tdBook.getBookname());
            opl.setTotalfee(order.getTotalfee());
            opl.setPaystatus(PayStatus.success.getName());
            opl.setUserpaystatus(PayType.ALI_WEB.getName());
            opl.setWebhookstatus(PayStatus.success.getName());
            tdOnlinePayLogMapper.insert(opl);

            TdWalletPayLog twp = new TdWalletPayLog();
            twp.setBillno(order.getBillno());
            twp.setCreatedate(new Date());
            twp.setCreateuser(tbUser.getUsername());
            twp.setPaystatus(PayStatus.success.getName());
            twp.setReturntype(PayStatus.success.getName());
            twp.setTitle(tdSection.getSectionname());
            twp.setTotalfee(tdSection.getTotalfee());
            twp.setUserpaystatus(PayType.ALI_WEB.getName());
            twp.setPaytype(order.getPaytype());
            twp.setUuid(tbUser.getUuid());
            twp.setWebhookstatus(PayStatus.success.getName());
            tdWalletPayLogService.insert(twp);

            tbUser.setBalance(tbUser.getBalance() - tdSection.getTotalfee());
            tbUserService.update(tbUser);
            tdBook.setSell(tdBook.getSell()+1);
            tdBookService.updateByPrimaryKey(tdBook);
        }
        return R.ok();
    }

    /**
     * 查询用户已经购买章节
     *
     * @param id bookid
     * @return
     */
    @PostMapping("pay")
    public R pay(@LoginUser TbUser tbUser, Integer id) {
        TdBook tdBook = tdBookService.selectByPrimaryKey(id);
        Map<String, Object> map = new HashMap<>();
        map.put("bookUUID", tdBook.getId());
        List<TdSection> tdSectionList2 = new ArrayList<>();
        List<TdSection> tdSectionList = tdSectionService.queryList(map);
        for (int i = 0; i < tdSectionList.size(); i++) {
            map.put("orderStatus", PayStatus.success.getName());
            map.put("uuid", tbUser.getUuid());
            map.put("sectionid", tdSectionList.get(i).getId());
            if (tdOrderService.queryList(map).size() > 0) {
                tdSectionList2.add(tdSectionList.get(i));
            }
        }
        return R.ok().put("tdSection", tdSectionList2);
    }

    /**
     * 查询单条订单的详情信息
     *
     * @param id 订单ID
     * @return
     */
    @PostMapping("find")
    public R find(@LoginUser TbUser tbUser, Integer id) {
        TdOrder order = tdOrderService.selectByPrimaryKey(id);
        return R.ok().put("order", order);
    }

    /**
     * 获取我的订单列表
     *
     * @return
     */
    @PostMapping("list")
    public R getOrderList(@LoginUser TbUser tbUser, @RequestParam Map<String, Object> map) {
        List<TdOrder> orderList = null;
        map.put("uuid", tbUser.getUuid());
        Query query = new Query(map);
        orderList = tdOrderService.queryList(query);
        int total = tdOrderService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(orderList, total, query.getLimit(), query.getPage());
        return R.ok().put("orderList", pageUtil);
    }

    /**
     * 删除我的订单
     *
     * @param id 订单ID
     * @return
     */
    @PostMapping("del")
    public R delOrder(@LoginUser TbUser tbUser, int id) {
        return R.ok().put("order", tdOrderService.selectByPrimaryKey(id));
    }

//    public static void main(String[] args){
//        String arr = "['36','37','38']";
//        JSONArray ja = JSONArray.fromObject(arr);
//        for (int i = 0;i<ja.size();i++){
//            System.out.println(ja.get(i));
//        }
//    }
}
